package ru.spbsu.electromenu.storage.db;

import org.springframework.jdbc.core.RowMapper;
import ru.spbsu.electromenu.model.Tag;
import ru.spbsu.electromenu.storage.TagStorage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: 3/20/11
 * Time: 1:31 PM
 *
 * @author Artem Titov
 */
public class TagDbStorage extends AbstractDbStorage implements TagStorage {

    private final RowMapper<Tag> TAG_ROW_MAPPER = new RowMapper<Tag>() {

        @Override
        public Tag mapRow(ResultSet rs, int i) throws SQLException {
            final Tag tag = new Tag();
            tag.setId(rs.getInt("Id"));
            tag.setName(rs.getString("Name"));
            return tag;
        }
    };

    @Override
    public Tag get(int id) {
        return jdbcTemplate.queryForObject("select * from `Tag` where `Id`=?", TAG_ROW_MAPPER, id);
    }

    @Override
    public int put(Tag tag) {
        return jdbcTemplate.update("insert into `Tag`(`Name`) values (?)", tag.getName());
    }

    @Override
    public int update(Tag tag) {
        return jdbcTemplate.update("update `Tag` set `Name`=? where `Id`=?", tag.getName(), tag.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from `Tag` where `Id`=?", id);
    }

    @Override
    public List<Tag> getALl() {
        return jdbcTemplate.query("select * from `Tag`", TAG_ROW_MAPPER);
    }
}
